//
//  ALUserAccountViewModel.swift
//  ALSinaWeiBoSwift
//
//  Created by 柴瑞军 on 16/4/11.
//  Copyright © 2016年 myCompany. All rights reserved.
//

import UIKit

class ALUserAccountViewModel: NSObject {
static let userAccountViewModel = ALUserAccountViewModel()
    
   private override init() {
       super.init()
    
    // 单例的init只执行一次
    // 加载账号
    userAccount = readUserData()
    }
    
    
    /// 账号模型，只要那到单例就可以访问到,全局通用.
    var userAccount: ALUserAccount?
    
//    判断用户是否登录的属性
    var userLogin: Bool {
        get{
          return userAccount != nil
        }
    }
    
    
    
//    定义闭包通过参数进行传递
    func loadAccessToken(code:String,loadAcessTokenSuccessCallBack:(error:NSError?)->()){
        //    在此处获取access_Token,透过post方式
        //        1.url
        let urlString = accessTokenURLString
        
        let parameters = [
            "client_id":client_id,
            "client_secret":client_secret,
            "grant_type":grant_type,
            "code":code,
            "redirect_uri":redirect_uri
        ];
        ALNetWorkTool.shareInstance.POST(urlString, parameters: parameters, progress: nil, success: { (task, responseObject) -> Void in
 
            let result = responseObject as? [String:AnyObject]
            //            将获取到的数据进行字典转模型
            //            判断如果数据转成功的时候就进行字典转模型
            if let dict = result {
                
                // 字典转模型,并且赋值给属性
                self.userAccount = ALUserAccount(dict: dict)
                self.saveUserAccount()
                
                //                由于铜通过下面的答应方式进行的打印则打印出来的结果是字典转模型成功,<ALSinaWeiBoSwift.ALUserAccount: 0x7fef0e01a980>  我们要的是打药出对象,因此重写description方法,
                
                print("字典转模型成功,\(self.userAccount)")
//                获取token成功回调
                loadAcessTokenSuccessCallBack(error: nil)
            }
            
        }) { (task, error) -> Void in
            ALPrint("accessToken 请求失败: \(error)")
               loadAcessTokenSuccessCallBack(error: error)
        }
        
    }
    //        归档的方法
    private func saveUserAccount(){
        // 路径
        // 归档
        if let userAccount = self.userAccount{
        NSKeyedArchiver.archiveRootObject(userAccount, toFile: accountPath)
        }
    }
//解档
    private func readUserData()->ALUserAccount?{

//        解档帐号,有可能有值,有可能没有值
       let userAccount =  NSKeyedUnarchiver.unarchiveObjectWithFile(accountPath) as? ALUserAccount
//        ALPrint("\(userAccount)")
//        测试过期时间
        if  let account = userAccount  where account.expiresDate?.compare(NSDate())==NSComparisonResult.OrderedDescending{
//            ALPrint("没有过期:\(account)")
            return account
        }
        return nil
    }
//    获取用户信息
    func loadUserInfo(loadUserInfoCallback: (error: NSError?) -> ()){
//    加载数据的url
        guard let access_token = userAccount?.access_token else{
        ALPrint("userAccunt或者Access_token没有值")
            let error = ALNetworkError.accessTokenEmpty.error()
            loadUserInfoCallback(error:error)
            return
        }
        guard let uid = userAccount?.uid else{
            ALPrint("userAccount或者uid没有值")
            let error = ALNetworkError.uidEmpty.error()
            
            loadUserInfoCallback(error: error)
            return
        }
        let url = "https://api.weibo.com/2/users/show.json"
        
        let paragram  = [
        "access_token" : access_token,
            "uid" : uid
        ]
        
        
//        请求加载数据
        ALNetWorkTool.shareInstance.GET(url, parameters: paragram, progress: nil, success: { (task, responseObject) in
            if let dict = responseObject as? [String: AnyObject] {
                // 将获取到得数据赋值给当前账号
                self.userAccount?.screen_name = dict["screen_name"] as? String
                self.userAccount?.avatar_large = dict["avatar_large"] as? String
                
                // 将当前对象保存到沙盒中
                self.saveUserAccount()
//            ALPrint("\(responseObject)")
                loadUserInfoCallback(error: nil)
            }
            }) { (task, error) in
            ALPrint("\(error)")
                loadUserInfoCallback(error: error)
        }
    
    }
}
